package com.jiubanqingchen.future.org.tool.jwt;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jiubanqingchen.future.model.models.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtService {

	private static Logger logger = LoggerFactory.getLogger(JwtService.class);
    /** 签名密匙 */
    public static String SECRET = "jiubanqingchen@2019";
    public static String ISSUER = "user";
    /** 失效时间为1小时 */
    public static int HOUR = 10;

    /**
     * @Title: createToken
     * @Description: (创建token)
     * @param @param  userId
     * @param @return
     * @param @throws Exception 参数
     * @return String 返回类型
     * @throws @author LightDust
     * @date 2019年1月3日 上午11:03:06
     */
	public static String createToken(User user) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("type", "JWT");
		user.setUserPassword("");//置空密码
		// 使用 HS256算法
		String token = null;
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER).withExpiresAt(DateUtil.offsetHour(new Date(),HOUR))
					.withClaim("user", JsonKit.toJson(user));
			 token= builder.sign(algorithm);
		} catch (Exception e) {
			logger.error("token生成失败");
		} // 设置携带参数以及签名
		return token;
	}

	/**
	 * @Title: verifyToken
	 * @Description: (解析token,得到)
	 * @param @param  token
	 * @param @return
	 * @param @throws Exception 参数
	 * @return User 返回类型
	 * @throws @author LightDust
	 * @date 2019年1月3日 上午11:03:28
	 */
	public static User verifyToken(String token) {
		if (StrKit.isBlank(token)) {
			return null;
		}
		JWTVerifier jWTVerifier = null;
		try {
			jWTVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
			DecodedJWT jwtToken = jWTVerifier.verify(token);
			String userJsonString = jwtToken.getClaim("user").asString();
			if(userJsonString!=null) {
				return JsonKit.parse(userJsonString, User.class);
			}
		} catch (Exception e) {
			logger.error("token解析失败:token超时");
			e.printStackTrace();
		}
		return null;
	}
}
